<template>
  <div>
    <n-card :bordered="false">
      <!-- 页面标题和操作栏 -->
      <div class="header-bar">
        <h2>AGV配置管理</h2>
        <n-button type="primary" :loading="loading" @click="handleAdd_AGV_car">添加AGV</n-button>
      </div>
      <n-data-table :loading="loading" :columns="columns" :data="DataList" :pagination="pagination" />
    </n-card>
    <n-layout class="content">
      <n-flex justify="end">
        <n-button class="text_size" type="info" :loading="loading" @click="fetchList">刷新数据</n-button>
        <n-tag class="text_size">每页显示数据量</n-tag>
        <n-select class="text_size" v-model:value="pagination.pageSize" :options="options" />
      </n-flex>
    </n-layout>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, h, onMounted } from "vue";
import { NSpace, NTag, NButton, NSelect, NFlex, NDataTable, NLayout, useDialog, useMessage, NCard } from "naive-ui";
import { useRouter } from "vue-router";
import { API_URLS } from '../../utils/apiConfig';

const router = useRouter();
const message = useMessage();
const dialog = useDialog();

//每页显示数据 选择项
const options = [
  { label: "5条", value: 5 },
  { label: "10条", value: 10 },
  { label: "15条", value: 15 },
  { label: "40条", value: 40, disabled: true },
];

// 分页参数
const pagination = ref({
  pageSize: 10,
});

// 状态管理
const loading = ref(false);
const error = ref(null);

// agv car list参数datatable
const DataList = ref([]);

// 使用配置文件中的API地址
const Enable_API_URL = API_URLS.agv.enable;
const Disable_API_URL = API_URLS.agv.disable;
const AGV_car_API = API_URLS.agv.base;

// 获取AGV列表数据
const fetchList = async () => {
  loading.value = true;
  error.value = null;

  try {
    const response = await axios.get(API_URLS.agv.page, {
      params: {
        page: 1,
        page_size: 1000,
      },
    });

    if (response.data.code === 200) {
      DataList.value = response.data.data;
    } else {
      error.value = `获取数据失败: ${response.data.msg || "未知错误"}`;
    }
  } catch (err) {
    error.value = `网络错误: 无法连接到服务器 (${err.message})`;
  } finally {
    loading.value = false;
  }
};

// 初始化页面
onMounted(() => {
  fetchList();
});

// 表格列定义
const columns = [
  { title: "AGV编号", key: "agv_index" },
  { title: "AGV类型", key: "agv_type" },
  { title: "IP地址", key: "remote_host" },
  { title: "本机端口", key: "local_port" },
  { title: "远程端口", key: "remote_port" },
  { title: "响应超时ms", key: "timeout" },
  { title: "发送间隔ms", key: "timesend" },
  {
    title: "启用状态",
    key: "isenable",
    render: (row) => {
      const is_Enable = ref(false);
      if (row.isenable == 1) {
        is_Enable.value = true;
      }
      const color = is_Enable.value ? "green" : "red";
      const text = is_Enable.value ? "启用" : "禁用";

      // 创建圆形指示器
      const circle = h("span", {
        style: {
          width: "20px",
          height: "20px",
          borderRadius: "50%",
          backgroundColor: color,
          display: "inline-block",
          marginRight: "6px",
        },
      });

      // 创建文本元素
      const textNode = h("span", text);

      // 组合成一个容器元素
      return h(
        "div",
        {
          style: {
            display: "flex",
            alignItems: "center",
            justifyContent: "flex-start",
          },
        },
        [circle, textNode]
      );
    },
  },
  {
    title: "操作",
    key: "action",
    // width: 160,
    render(row) {
      return h(
        NSpace,
        { size: "small" },
        {
          default: () => [
            h(NButton, { size: "small", type: "success", onClick: () => update_AGV_car(row.id, "enable") }, { default: () => "启用" }),
            h(NButton, { size: "small", type: "error", onClick: () => update_AGV_car(row.id, "disable") }, { default: () => "禁用" }),
          ],
        }
      );
    },
  },
  {
    title: "删除",
    key: "delete",
    render(row) {
      return h(
        NSpace,
        { size: "small" },
        {
          default: () => [
            h(NButton, { size: "small", onClick: () => handleEdit_AGV_car(row.id) }, { default: () => "编辑" }),
            h(NButton, { size: "small", type: "error", onClick: () => handleDelete_AGV_car(row.id) }, { default: () => "删除" }),
          ],
        }
      );
    },
  },
];

// 处理配置操作
const update_AGV_car = async (id, action) => {
  loading.value = true;
  error.value = null;
  try {
    const response = await axios.post(action === "enable" ? Enable_API_URL : Disable_API_URL, {}, { params: { id: id } });

    if (response.data.code === 200) {
      message.success(response.data.msg);
    } else {
      message.error(`获取数据失败: ${response.data.msg || "未知错误"}`);
    }
  } catch (err) {
    message.error(`网络错误: 无法连接到服务器 (${err.message})`);
  } finally {
    loading.value = false;
    //重新加载数据
    fetchList();
  }
};

// 处理删除操作 弹出提示框
const handleDelete_AGV_car = async (id) => {
  dialog.warning({
    title: "警告",
    content: "确认删除？",
    positiveText: "删除",
    negativeText: "取消",
    draggable: true,
    onPositiveClick: () => {
      Delete_AGV_car_index(id);
    },
    onNegativeClick: () => {
      message.error("已取消");
    },
  });
};

// 处理删除操作
const Delete_AGV_car_index = async (id) => {
  loading.value = true;
  try {
    const response = await axios.delete(`${API_URLS.agv.delete}/${id}`, { params: {} });

    if (response.data.code === 200) {
      message.success("站点删除成功");
      //重新加载数据
      fetchList();
    } else {
      message.error(`获取数据失败: ${response.data.msg || "未知错误"}`);
    }
  } catch (err) {
    message.error(`网络错误: 无法连接到服务器 (${err.message})`);
  } finally {
    loading.value = false;
  }
};

// 添加配置
const handleAdd_AGV_car = () => {
  router.push("/AGV/AGV_car_add");
};

// 编辑配置
const handleEdit_AGV_car = (id) => {
  router.push({ path: `/AGV/AGV_car_edit/${id}` });
};
</script>

<style scoped>
.text_size {
  width: 150px;
  height: 35px;
  text-align: center;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
